package com.blog.controller;

import com.blog.pojo.Followee;
import com.blog.pojo.User;
import com.blog.service.FolloweeService;
import com.blog.service.UserService;
import com.blog.service.impl.FolloweeServiceImpl;
import com.blog.service.impl.UserServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import static java.time.LocalDateTime.now;
@WebServlet("/followeeServlet")
public class FolloweeServlet extends BaseServlet{
    private FolloweeService followeeService = new FolloweeServiceImpl();
    private UserService userservice = new UserServiceImpl();
    // 添加关注+取消关注
    public String addFollowee(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取作者id
        String followeeId = request.getParameter("followeeId");
        //登录验证
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (user == null) {
            request.setAttribute("msg", "请先登录");
            return "forward:/login.jsp";
        }
        //获取登录用户id
        int uId = user.getId();
        int followeeIdInt = Integer.parseInt(followeeId);
          if(uId==followeeIdInt){
         request.setAttribute("msg", "不能关注自己");
         return "forward:/userProfile.jsp";
     }
        //获取followee表的uid
        Followee followee1 = followeeService.findByUserIdAndFolloweeId(uId, followeeIdInt);
        //已关注
        if (followee1 != null) {
            request.setAttribute("msg", "已关注");
            boolean delete = followeeService.delete(uId, followeeIdInt);
            if (delete) {
                //A（登录人，uId）关注B（被关注人，followee）
                //取消关注成功---A不在关注B--->A的关注数减1，B的粉丝数减1
                //A的关注数减1
                int afollowee = followeeService.reduceFolloweeCount(uId);
                //B的粉丝数减1
                int bfan = followeeService.reduceFanCount(followeeIdInt);

                //经验值减少10
                boolean b = userservice.reduceExperience(followeeIdInt, 10);
                if (!b) {
                    request.setAttribute("msg", "经验值减少失败");
                    return "forward:/error.jsp";
                }
                int experiencePoints = userservice.findExperience(followeeIdInt);

                //B的关注总数
                int bfolloweeCount = followeeService.findFolloweeCount(followeeIdInt);
                //B的粉丝总数
                int bfanCount = followeeService.findFanCount(followeeIdInt);
                request.setAttribute("followeeCount",bfolloweeCount);
                request.setAttribute("fanCount",bfanCount);
                request.setAttribute("experiencePoints", experiencePoints);
                    request.setAttribute("msg", "取消关注成功");
              } else {
                    request.setAttribute("msg", "取消关注失败");
                }
            return "forward:/articleServlet?method=userProfile&userId=" + followeeIdInt;

        }

        //添加关注
        Followee followee = new Followee();
        followee.setuId(uId);
        followee.setFolloweeId(followeeIdInt);
        //调用 service
        followeeService.addFollowee(followee);
        //A（登录人，uId）关注B（被关注人，followee）
        //关注成功---A关注B--->A的关注数加1，B的粉丝数加1
        //A的关注数加1
        int afollowee = followeeService.addFolloweeCount(uId);
        //B的粉丝数加1
        int bfan = followeeService.addFanCount(followeeIdInt);

        //经验值加10
        boolean b = userservice.addExperience(followeeIdInt, 10);
        if (!b) {
            request.setAttribute("msg", "经验值增加失败");
            return "forward:/error.jsp";
        }
        int experiencePoints = userservice.findExperience(followeeIdInt);

        //B的关注总数
        int bfolloweeCount = followeeService.findFolloweeCount(followeeIdInt);
        //B的粉丝总数
        int bfanCount = followeeService.findFanCount(followeeIdInt);
        //返回关注数和粉丝数
        request.setAttribute("followeeCount",bfolloweeCount);
        request.setAttribute("fanCount",bfanCount);
        request.setAttribute("experiencePoints", experiencePoints);
        request.setAttribute("msg", "关注成功");

        //跳转个人主页
        return "forward:/articleServlet?method=userProfile&userId=" + followeeIdInt;
    }

    //粉丝列表(uid)

    public String findFanList(HttpServletRequest request, HttpServletResponse response) {
        String followeeId = request.getParameter("followeeId");
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (user == null) {
            request.setAttribute("msg", "请先登录");
            return "forward:/login.jsp";
        }
      int followeeIdInt = Integer.parseInt(followeeId);
        List<Followee> fanList = followeeService.findFanList(followeeIdInt);
        for (Followee followee : fanList) {
            User byId = userservice.findById(followee.getuId());
            followee.setUsername(byId.getUsername());
        }
        request.setAttribute("fanList", fanList);
        return "forward:/fanList.jsp";
    }

    //关注列表(followeeId)
    public String findFolloweeList(HttpServletRequest request, HttpServletResponse response) {
        //1.获取用户id
        String followeeId = request.getParameter("followeeId");
        //2.登录验证
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (user == null) {
            request.setAttribute("msg", "请先登录");
            return "forward:/login.jsp";
        }

        List<Followee> followeeList = followeeService.findFolloweeList(Integer.parseInt(followeeId));
        for (Followee followee : followeeList) {
            User byId = userservice.findById(followee.getFolloweeId());
            followee.setUsername(byId.getUsername());

        }
        request.setAttribute("followeeList", followeeList);
        return "forward:/followeeList.jsp";
    }

    public void getFolloweeCount(HttpServletRequest request,HttpServletResponse response) throws IOException {
        //1.获取用户id
        String userId = request.getParameter("userId");

        int userIdInt = Integer.parseInt(userId);

        //获取关注数（service）
        int followeeCount = followeeService.findFolloweeCount(userIdInt);
//        request.setAttribute("followeeCount", followeeCount);
//        return "forward:/userProfile.jsp";

        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.write(String.valueOf(followeeCount));

        out.flush();
        out.close();

    }

  public void getFanCount(HttpServletRequest request,HttpServletResponse response) throws IOException {
      //1.获取用户id
      String userId = request.getParameter("userId");
      int userIdInt = Integer.parseInt(userId);
        //获取粉丝数（service）
        int fanCount = followeeService.findFanCount(userIdInt);
      response.setContentType("application/json;charset=UTF-8");
      PrintWriter out = response.getWriter();
      out.write(String.valueOf(fanCount));

      out.flush();
      out.close();

    }

//public void getFanCount (HttpServletRequest request, HttpServletResponse response) throws IOException {
//
//    String userIdStr = request.getParameter("userId");
//    int userIdInt = 0;
//    try {
//        userIdInt = Integer.parseInt(userIdStr);
//    } catch (NumberFormatException e) {
//        response.setContentType("application/json;charset=UTF-8");
//        PrintWriter out = response.getWriter();
//        out.write("{\"error\":\"无效的用户ID格式\"}");
//        out.flush();
//        out.close();
//        return;
//    }
//    int followeeCount = followeeService.findFanCount(userIdInt);
//    response.setContentType("application/json;charset=UTF-8");
//    PrintWriter out = response.getWriter();
//    out.write(String.valueOf(followeeCount));
//    out.flush();
//    out.close();
//}
//
//
//public void getFolloweeCount(HttpServletRequest request, HttpServletResponse response) throws IOException {
//    String userIdStr = request.getParameter("userId");
//    int userIdInt = 0;
//    try {
//        userIdInt = Integer.parseInt(userIdStr);
//    } catch (NumberFormatException e) {
//        response.setContentType("application/json;charset=UTF-8");
//        PrintWriter out = response.getWriter();
//        out.write("{\"error\":\"无效的用户ID格式\"}");
//        out.flush();
//        out.close();
//        return;
//    }
//    int followeeCount = followeeService.findFolloweeCount(userIdInt);
//    response.setContentType("application/json;charset=UTF-8");
//    PrintWriter out = response.getWriter();
//    out.write(String.valueOf(followeeCount));
//    out.flush();
//    out.close();
//}


    public void getExperiencePoints(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter("id");
        int uId = Integer.parseInt(id);
        int experiencePoints = userservice.findExperience(uId);

        response.setContentType("text/plain");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        out.print(experiencePoints);
        out.flush();
    }
}
